<?php
// +----------------------------------------------------------------------
// | 前台函数库
// +----------------------------------------------------------------------
// | @link ( http://www.yurnero.net )
// +----------------------------------------------------------------------
// | @copyright
// +----------------------------------------------------------------------
// | @licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | @author Haijun Wu <nicholasinlove@126.com>
// +----------------------------------------------------------------------
// | $Id: common.php 104 2011-04-29 03:45:27Z nicholasinlove1986@gmail.com $
// +----------------------------------------------------------------------


if (!defined('IN_BLOG')) {
    die('Hacking attempt');
}

require_cache (ROOT_PATH.'Includes/common.inc.php');

/**
 * 创建静态缓存文件(前台)
 *
 * @access  public
 * @return  void
 */
function create_static_caches() {
	$path  =  ROOT_PATH . STATIC_CACHES_DIR;
	//日历
	if (!file_exists($path.'calendar_static.php')) {
		$cal   = $path.'calendar_static.php';
		import("@.ORG.Calendar");
		$y = Calendar::local_date('Y');
		$m = Calendar::local_date('m');	
		$date = new Calendar($y,$m);
		$start_time = local_mktime(0,0,0,$m,1,$y);
		$end_time   = local_mktime(0,0,0,$date->nextMonth,1,$date->nextYear);
		$num  = get_posts_from_date($start_time,$end_time);
		$html = $date->outPut($num);	
		if($fp = @fopen($cal, 'wb')) {
			$cachedata = "\$html = unserialize('".addcslashes(serialize($html), '\\\'')."');";
			@fwrite($fp, "<?php\n//nblog cache file\n//Created on " . date('Y-m-d H:i:s',time()) . "\n\nif (!defined('IN_BLOG')) exit('Hacking attempt');\n\n\$expiration='".(time() + 600)."';\r\n".$cachedata."\r\n?>");
			@fclose($fp);
			@chmod($cal, 0777);
		}
	}
	//日志分类
	if (!file_exists($path.'category_static.php')) {
		$cat  = D('Category','Admin');
		$data = $cat->getCatArray();
		f_static_cache('category_static',$data ,$path); 
	}
	//过滤和排序所有日志分类，返回一个带有缩进级别的数组
	if (!file_exists($path.'cat_option_static.php')) {
		$cat  = D('Category','Admin');
		$data = f_static_cache('category_static','',$path);
		$data = $cat->getCatOptions($data,$cat_id);
		f_static_cache('cat_option_static',$data ,$path); 
	}
	//隐藏不可显示的分类,经过过滤和排序处理,带有缩进级别的数组
	if (!file_exists($path.'category_isshow_static.php')) {
		$cat  = D('Category','Admin');
		$data = $cat->getCatList(0,0,0,false,false);
		foreach ($data as $key =>$v) {
			foreach ($v as $k=>$c){
				if($k!='category_id'&&$k!='category_url'&&$k!='category_title'&&$k!='posts_num'&&$k!='level') {
					unset($data[$key][$k]);
				}
			}
		}
		f_static_cache('category_isshow_static',$data ,$path); 
	}
//友情链接
	if (!file_exists($path.'links_static.php')) {
		$links = M('Links');
		$map = array();
		$map['link_status'] = 1; 
		$map['link_visible'] = 1;
		$data = $links->field('link_url,link_name,link_description')->where($map)->order('link_sort asc')->limit(C('links_num'))->findAll();
		f_static_cache('links_static',$data ,$path); 		
	}
	//最新评论	
	if (!file_exists($path.'comment_static.php')) {
		$com = M('Comment');
		$map = array();
		$map[C('DB_PREFIX').'comment.comment_status'] = 1; 
		$map[C('DB_PREFIX').'comment.comment_visible'] = 1;
		$map[C('DB_PREFIX').'comment.comment_type'] = array('neq',2);
		$map[C('DB_PREFIX').'posts.posts_status'] = 1;
		if (C('remark')) {
			$map[C('DB_PREFIX').'comment.comment_remark'] = 1;
		}
		$data = $com->where($map)->field(C('DB_PREFIX').'comment.comment_id,'.C('DB_PREFIX').'comment.posts_id,'.C('DB_PREFIX').'posts.posts_title,'.C('DB_PREFIX').'posts.posts_url,'.C('DB_PREFIX').'comment.comment_content,'.C('DB_PREFIX').'comment.comment_author,'.C('DB_PREFIX').'comment.comment_email,'.C('DB_PREFIX').'comment.comment_url')->join(C('DB_PREFIX').'posts ON '.C('DB_PREFIX').'posts.posts_id = '.C('DB_PREFIX').'comment.posts_id')->order('comment_id desc')->limit(C('recent_comments_num'))->findAll();
		foreach ($data as $k=>$v) {
			//$data[$k]['comment_short_content'] = msubstr(htmlspecialchars(addslashes($v['comment_content'])),0,C('recent_comments_limit'));
			$comment_excerpt = preg_replace('/(\r\n)|(\n)/', '', $v['comment_content']); // 消灭换行符
			$comment_excerpt = rc_remove_blockquotes($comment_excerpt); // 消灭所有 blockquote 内容
			$comment_excerpt = preg_replace('/\<(.+?)\>/', '', $comment_excerpt); // 消灭所有标签
			$data[$k]['comment_short_content'] = msubstr($comment_excerpt, 0, C('recent_comments_limit'));
			$data[$k]['comment_ellipsis']  = (strpos($data[$k]['comment_short_content'],"...")) ? 1 : 0 ;
			$data[$k]['comment_email'] = get_gravatar($data[$k]['comment_email'], $s = 80, $d = C('avatar_default'), $r = C('avatar_rating'));
		}
		f_static_cache('comment_static',$data ,$path);
	}
	//日志归档 默认日期对应日志数
	if (!file_exists($path.'posts_static.php')) {
		$posts = M('Posts');
		$map = array();
		$map['posts_status'] = 1; 
		$map['posts_draft'] = 1;
		$map['posts_type'] = 1;
		$data = $posts->where($map)->field('posts_date, count(posts_id) as num')->order('posts_date desc')->group('posts_date')->select();
		$newarr = array();
		foreach ($data as $key => $v) {
				$newarr[$v['posts_date']] = $v['num'];	
		}
		f_static_cache('posts_static',$newarr ,$path);
	}
	//标签
	if (!file_exists($path.'tag_static.php')) {
		$tag  = D('Tag','Admin');
		$data = $tag->getTagArray();
		foreach ($data as $key =>$v) {
			foreach ($v as $k=>$c){
				if($k=='tag_addtime') {
					unset($data[$key][$k]);
				}
			}
		}
		f_static_cache('tag_static',$data ,$path);
	}
	//统计信息
	if (!file_exists($path.'statistics_static.php')) {
		$posts = M('Posts');
		$com   = M('Comment');
		$cat   = M('Category');
		$tag   = M('Tag');
		$tb    = M('Trackback');
		$link  = M('Links');
		//日志
		$posts_map = array();
		$posts_map['posts_status'] = 1; 
		$posts_map['posts_draft'] = 1;
		$posts_map['posts_type'] = 1;
		$posts_num = $posts->where($posts_map)->count();
		//评论
		$comment_sql = '';
		$comment_sql .= ' comment_status = 1 and comment_visible = 1 and comment_type <> 2 ';
		if (C('remark')) {
			$comment_sql .=  ' and comment_remark = 1 ';
		}
		$comment_num = $com->where($comment_sql)->count();
		//留言
		$guestbook_map = array();
		//$guestbook_map['comment_status'] = 1; 
		$guestbook_map['comment_visible'] = 1;
		$guestbook_map['comment_type'] = 2;
		/*if (C('remark')) {
			$comment_map['comment_remark'] = 1;
		}*/
		$guestbook_num = $com->where($guestbook_map)->count();
		//分类
		$category_num = $cat->where('category_isshow = 1')->count();
		//标签
		$tag_num = $tag->count();
		//附件
		$real_list = array();
		$folder = opendir(ROOT_PATH . UPLOAD_DIR);
		while ($file = readdir($folder)) {
			if ((strpos($file,'.doc') || strpos($file,'.pdf') || strpos($file,'.rar') || strpos($file,'.zip'))!== false) {
				$real_list[] = $file;
			}
		}
		$attachment_num = count($real_list);
		//引用通告
		$tb_map = array();
		$tb_map['tb_visible'] = 1;
		$trackback_num = $tb->where($tb_map)->count();
		//访问量
		$today_num = C('today_pv');
		$total_num = C('total_pv');
		$statistics_addtime = gmtime();
		//友情链接
		$link_map = array();
		$link_map['link_status'] = 1; 
		$link_map['link_visible'] = 1;
		$link_num = $link->where($link_map)->count();
		 
		$data = array(
			'posts_num' => !empty($posts_num) ? intval($posts_num) : 0,
			'comment_num' => !empty($comment_num) ? intval($comment_num) : 0,
			'guestbook_num' => !empty($guestbook_num) ? intval($guestbook_num) : 0,
			'category_num' => !empty($category_num) ? intval($category_num) : 0,
			'tag_num' => !empty($tag_num) ? intval($tag_num) : 0,
			'attachment_num' => !empty($attachment_num) ? intval($attachment_num) : 0,
			'trackback_num' => !empty($trackback_num) ? intval($trackback_num) : 0,
			'link_num' => !empty($link_num) ? intval($link_num) : 0,
			'today_num' => !empty($today_num) ? intval($today_num) : 0,
			'total_num' => !empty($total_num) ? intval($total_num) : 0,
			'statistics_addtime' => $statistics_addtime,
		);
		f_static_cache('statistics_static',$data ,$path);
	}
}

/**
 * 标签着色,字体大小,加粗
 *
 * @access  public
 *
 * @return  string
 */
function tag_cloud(&$tags) {

	$tagmark = array(
		array('color'=>'#666666','size'=>'0.8em','size_for'=>'10.5pt','ifbold'=>1),
		array('color'=>'#333333','size'=>'1.0em','size_for'=>'12pt','ifbold'=>0),
		array('color'=>'#006699','size'=>'1.2em','size_for'=>'13.5pt','ifbold'=>1),
		array('color'=>'#CC9900','size'=>'1.4em','size_for'=>'15pt','ifbold'=>0),
		array('color'=>'#666633','size'=>'1.6em','size_for'=>'16.5pt','ifbold'=>1),
		array('color'=>'#993300','size'=>'1.8em','size_for'=>'18pt','ifbold'=>0),
		array('color'=>'#669933','size'=>'2.0em','size_for'=>'19.5pt','ifbold'=>1),
		array('color'=>'#197B30','size'=>'2.2em','size_for'=>'21pt','ifbold'=>0),
		array('color'=>'#FF6600','size'=>'2.4em','size_for'=>'22.5pt','ifbold'=>1),
	);
	$maxlevel = count($tagmark);
	$tcount = $scount = array();
	foreach($tags as $val) {
		$tcount[] = $val['posts_num'];
	}
	$tcount = array_unique($tcount);

	sort($tcount);

	$tempcount = count($tcount);
	$per = $maxlevel >= $tempcount ? 1 : $maxlevel / ($tempcount - 1);

	foreach ($tcount as $key => $val) {
		$lvl = floor($per * $key);
		$scount[$val] = $lvl;
	}
	foreach ($tags as $key => $val) {
		$lvl = $scount[$val['posts_num']];	
		$tags[$key]['color'] = $tagmark[$lvl]['color'];
		$tags[$key]['size']  = $tagmark[$lvl]['size'];
		$tags[$key]['size_for']  = $tagmark[$lvl]['size_for'];
		$tags[$key]['bold']  = $tagmark[$lvl]['ifbold'];
	}
	shuffle($tags);
}

/**
 * 3D标签云
 *
 * @access  public
 *
 * @return  string
 */
function build_tag(&$tags) {
	
	$tag_cloud_data = '';
	$tag_cloud_data .= "<tags>";
	foreach($tags as $key =>$val) {
	   $tag_cloud_data .= '<a href="'.C('blog_domain').'Tag/'.$val['tag_url'].'/" class="tag-link-'.$val['tag_id'].'" title="'.$val['posts_num'].' 个话题" rel="tag" style="font-size:'.$val['size_for'].';">'.$val['tag_name'].'</a>';
	}
	$tag_cloud_data .= "</tags>";
	
	return url_encode($tag_cloud_data);
}

/**
 * 调用投票内容
 *
 * @access  public
 * @param   integer $id   投票的编号
 * @return  array
 */
function get_vote($id = '') {
	$v  = M('Vote');
	$vo = M('VoteOption');
	$db = M();
    /* 随机取得一个投票的主题 */
    if (empty($id)) {
        $timestamp = gmtime();		
		$vote = $v->field('*,rand() as rnd')->where("vote_visible = 1 AND vote_status = 1 AND
		 vote_starttime <= '$timestamp' AND vote_endtime >= '$timestamp'")->order('rnd desc')->limit(1)->find();	
    } else {
		$vote = $v->where("vote_visible = 1 AND vote_status = 1 AND vote_id = '$id'")->find();
    }

    if ($vote !== false && !empty($vote)) {
         /* 通过投票的ID,查询投票选项 */	 
		$sql_option = 'SELECT v.*, o.* ' . 'FROM ' . C('DB_PREFIX'). 'vote AS v, ' .C('DB_PREFIX') . 'vote_option AS o ' .
                      "WHERE o.vote_id = v.vote_id AND o.vote_id = '$vote[vote_id]' order by option_sort asc";
        $res = $db->query($sql_option);
		/* 总票数 */
		$option_num = $vo->where("vote_id = ".$vote['vote_id'])->sum('option_count');
		
		$arr = array();
        $count = 100;
        foreach ($res as $idx => $row) {
            if ($option_num > 0 && $idx == count($res) - 1) {
                $percent = $count;
            } else {
                $percent = ($row['vote_count'] > 0 && $option_num > 0) ? round(($row['option_count'] / $option_num) * 100) : 0;
                $count -= $percent;
            }
			if($percent < 0) {
				$percent = 0;
			}
            $arr[$row['vote_id']]['options'][$row['option_id']]['percent'] = $percent;
            $arr[$row['vote_id']]['vote_id']       = $row['vote_id'];
            $arr[$row['vote_id']]['vote_name']     = htmlspecialchars(stripslashes($row['vote_name']));
            $arr[$row['vote_id']]['vote_type']     = $row['vote_type'];
			$arr[$row['vote_id']]['vote_filterip'] = $row['vote_filterip'];
			$arr[$row['vote_id']]['vote_view']     = $row['vote_view'];
            $arr[$row['vote_id']]['vote_count']    = $row['vote_count'];
            $arr[$row['vote_id']]['options'][$row['option_id']]['option_id']    = $row['option_id'];
            $arr[$row['vote_id']]['options'][$row['option_id']]['option_name']  = $row['option_name'];
			$arr[$row['vote_id']]['options'][$row['option_id']]['option_url']   = $row['option_url'];
            $arr[$row['vote_id']]['options'][$row['option_id']]['option_count'] = $row['option_count'];
			$arr[$row['vote_id']]['options'][$row['option_id']]['option_sort']  = $row['option_sort'];
			$arr[$row['vote_id']]['options'][$row['option_id']]['option_color'] = get_uid(1); //随机颜色
			$arr[$row['vote_id']]['options'][$row['option_id']]['option_width'] = ($percent == 0) ? 1 : round($percent);//进度条长度
			if($arr[$row['vote_id']]['options'][$row['option_id']]['option_width'] == 100) {
				$arr[$row['vote_id']]['options'][$row['option_id']]['option_width'] = 99;
			}
        }

        $vote['vote_id'] = (!empty($vote['vote_id'])) ? $vote['vote_id'] : '';

        $ret = array('id' => $vote['vote_id'], 'content' => $arr);

        return $ret;
    }
}

/**
 * 获取所有已结束的投票存档
 *
 * @access  public
 * @param   integer $firstRow   分页
 * @param   integer $listRows   分页
 * @return  array
 */
function get_all_vote($firstRow,$listRows) {

	$v  = M('Vote');
	$vo = M('VoteOption');
	$db = M();
	$timestamp = gmtime();
	
    /* 获取符合条件的投票主题 */
	$vote = $v->where("vote_visible = 1 AND vote_status = 1 AND
		 vote_endtime <= '$timestamp'")->limit($firstRow.','.$listRows)->order('vote_id desc')->findAll();

    if ($vote !== false && !empty($vote)) {
		foreach ($vote as $vote) {
			 /* 通过投票的ID,查询投票选项 */	 
			$sql_option = 'SELECT v.*, o.* ' . 'FROM ' . C('DB_PREFIX'). 'vote AS v, ' .C('DB_PREFIX') . 'vote_option AS o ' .
						  "WHERE o.vote_id = v.vote_id AND o.vote_id = '$vote[vote_id]' order by option_sort asc";
			$res = $db->query($sql_option);
			/* 总票数 */
			$option_num = $vo->where("vote_id = ".$vote['vote_id'])->sum('option_count');
			
			$arr = array();
			$count = 100;
			foreach ($res as $idx => $row) {
				if ($option_num > 0 && $idx == count($res) - 1) {
					$percent = $count;
				} else {
					$percent = ($row['vote_count'] > 0 && $option_num > 0) ? round(($row['option_count'] / $option_num) * 100) : 0;
					$count -= $percent;
				}
				if($percent < 0) {
					$percent = 0;
				}
				$arr[$row['vote_id']]['options'][$row['option_id']]['percent'] = $percent;
				$arr[$row['vote_id']]['vote_id']        = $row['vote_id'];
				$arr[$row['vote_id']]['vote_name']      = htmlspecialchars(stripslashes($row['vote_name']));
				$arr[$row['vote_id']]['vote_type']      = $row['vote_type'];
				$arr[$row['vote_id']]['vote_filterip']  = $row['vote_filterip'];
				$arr[$row['vote_id']]['vote_view']      = $row['vote_view'];
				$arr[$row['vote_id']]['vote_count']     = $row['vote_count'];
				$arr[$row['vote_id']]['vote_starttime'] = date('F d, Y', $row['vote_starttime']).' @ '.date('g:i a', $row['vote_starttime']);	
				$arr[$row['vote_id']]['vote_endtime']   = date('F d, Y', $row['vote_endtime']).' @ '.date('g:i a', $row['vote_endtime']);
				$arr[$row['vote_id']]['options'][$row['option_id']]['option_id']    = $row['option_id'];
				$arr[$row['vote_id']]['options'][$row['option_id']]['option_name']  = $row['option_name'];
				$arr[$row['vote_id']]['options'][$row['option_id']]['option_url']   = $row['option_url'];
				$arr[$row['vote_id']]['options'][$row['option_id']]['option_count'] = $row['option_count'];
				$arr[$row['vote_id']]['options'][$row['option_id']]['option_sort']  = $row['option_sort'];
				$arr[$row['vote_id']]['options'][$row['option_id']]['option_color'] = get_uid(1); //随机颜色
				$arr[$row['vote_id']]['options'][$row['option_id']]['option_width'] = ($percent == 0) ? 1 : round($percent*0.9);//进度条长度
			}
	
			$vote['vote_id'] = (!empty($vote['vote_id'])) ? $vote['vote_id'] : '';
	
			$ret[] = array('id' => $vote['vote_id'], 'content' => $arr);
		
		}
		return $ret;
    }
}

/**
 * 检查是否已经提交过投票
 *
 * @access  private
 * @param   integer     $vote_id
 * @param   string      $ip_address
 * @return  boolean
 */
function vote_already_submited($vote_id, $ip_address) {
	$vi = M('VoteIp');
	$map = array();
	$map['ip_ip']   = $ip_address;
	$map['vote_id'] = $vote_id;
	$res = $vi->where($map)->count();
    return ($res > 0);
}

/**
 * 保存投票结果信息
 *
 * @access  public
 * @param   integer     $vote_id
 * @param   string      $option_id
 * @return  void
 */
function save_vote($vote_id,$option_id) {

    $v  = M('Vote');
	$vo = M('VoteOption');
	
    /* 更新投票主题的数量 */
	$v->setInc('vote_count', "vote_id = '$vote_id'");

    /* 更新投票选项的数量 */
	$vo->setInc('option_count', db_create_in($option_id, 'option_id'));
}

/**
 * 创建像这样的查询: "IN('a','b')";
 *
 * @access   public
 * @param    mix      $item_list      列表数组或字符串
 * @param    string   $field_name     字段名称
 *
 * @return   void
 */
function db_create_in($item_list, $field_name = '') {
    if (empty($item_list)) {
        return $field_name . " IN ('') ";
    } else {
        if (!is_array($item_list)) {
            $item_list = explode(',', $item_list);
        }
        $item_list = array_unique($item_list);
        $item_list_tmp = '';
        foreach ($item_list AS $item) {
            if ($item !== '') {
                $item_list_tmp .= $item_list_tmp ? ",'$item'" : "'$item'";
            }
        }
        if (empty($item_list_tmp)) {
            return $field_name . " IN ('') ";
        } else {
            return $field_name . ' IN (' . $item_list_tmp . ') ';
        }
    }
}

/**
 *  获得随机数
 *
 * @access     public
 * @param      string      $n       随机数长度
 * @return     string      $name    随机名称
*/
function get_uid($n) {
	$name = NULL;
	for ($j=0;$j<$n;$j++) {
		srand((double)microtime()*1000000);
		$randname=rand(!$j ? 1: 0,9);
		$name.=$randname;
	}
	return $name;
	$name = NULL;
}

/**
 * 分割ip
 */
function split_ip($str) {
	$str = str_replace("\n",",",$str);
	$str = str_replace("\r",",",$str);
	$str = str_replace(",,",",",$str);
	$str = explode(",",$str);
	return $str;
}

/**
 * 过滤用户名
 */
function filter_name($str) {
	if (strlen($str) > 30) {
		return 0;
	}
	$name_key = array("\\",'&',' ',"'",'"','/','*',',','<','>',"\r","\t","\n",'#','$','(',')','%','@','+','?',';','^');
	foreach($name_key as $val) {
		if (strpos($str,$val) !== false) { 
			return -1;
		}
	}
	if (C('filter_name')) {
		$ban_name = explode('|',trim(C('filter_name')));				
		foreach($ban_name as $val) {
			if (strpos($str,$val) !== false) {
				return -2;
			}
		}
	}
	return 1;
}

/**
 * 对用户传入的变量进行去除转义操作
 *
 * @access  public
 * @return  void
 */
function all_stripslashes() {
	if (get_magic_quotes_gpc()) {
		$_GET = stripslashes_deep($_GET);
		$_POST = stripslashes_deep($_POST);
		$_COOKIE = stripslashes_deep($_COOKIE);
		$_REQUEST = stripslashes_deep($_REQUEST);
	}
}

/**
 * Remove all blockquote nodes.
 */
function rc_remove_blockquotes($str) {
	// 开头和结尾的标记
	$start_pattern = '<blockquote';
	$end_pattern = '</blockquote>';
	// The number of blockquote nodes.
	$quote_count = substr_count(strtolower($str), $start_pattern);
	// If there are 0 blockquote nodes, do nothing.
	if ($quote_count <= 0) {
		return $str;
	// If there is 1 blockquote node, remove it.
	} else if($quote_count == 1) {
		$all_pattern = '/(\<blockquote(.*?)\>)(.*)(\<\/blockquote\>)/i';
		return preg_replace($all_pattern, '', $str);
	}
	// If there are more than 1 backquote nodes, pick the first ending tag.
	$end = strpos(strtolower($str), $end_pattern);
	// Loop all the blockquotes.
	while ($end) {
		// Get substring before first ending tag, and pick the last starting tag.
		$str_before_end = substr($str, 0, $end);
		$start = strrpos(strtolower($str_before_end), $start_pattern);
		// Replace blockquote node to separate.
		$sep = ' ';
		$str = substr_replace($str, $sep, $start, $end + strlen($end_pattern) - $start);
		// Pick next ending tag.
		$end = strpos(strtolower($str), $end_pattern);
	}
	return $str;
}

/**
 * 移除 HTML 字符串中, 除最外层的所有 blockquote
 * @param str			HTML 字符串
 */
function rc_remove_blockquotes_but_outermost($str) {
	// 开头和结尾的标记
	$start_pattern = '<blockquote';
	$end_pattern = '</blockquote>';
	// 出现的次数
	$quote_count = substr_count(strtolower($str), $start_pattern);
	// 如果出现次数为 0 或 1, 不进行任何处理, 直接返回
	if ($quote_count <= 1) {
		return $str;
	}
	// 如果出现次数大于 1, 创建数组以存放字符串段落
	$paragraphs = array();
	// 找到第一个结尾出现的位置
	$end = strpos(strtolower($str), $end_pattern);
	// 处理所有 blockquote
	while ($end) {
		// 获得尾部之前的子串
		$str_before_end = substr($str, 0, $end);
		// 结尾之前, 开始部分的出现次数
		$quote_count = substr_count(strtolower($str_before_end), $start_pattern);
		// 如果只有一个开头, 证明这是最外层引用, 放到段落数组里面
		if ($quote_count == 1) {
			$paragraph = substr($str, 0, $end + strlen($end_pattern));
			array_push($paragraphs, $paragraph);
			$sep = '';
			$str = substr_replace($str, $sep, 0, $end + strlen($end_pattern));
		// 如果出现多次开头部分
		} else {
			// 在子串中找到相应的开头位置
			$start = strrpos(strtolower($str_before_end), $start_pattern);
			// 将 blockquote 部分除去, 并用分隔符隔开
			$sep = ' ';
			$str = substr_replace($str, $sep, $start, $end + strlen($end_pattern) - $start);
		}
		// 找到下一个结尾的位置
		$end = strpos(strtolower($str), $end_pattern);
	}
	// 循环所有段落, 并组合成新的 HTML 字符串
	if ($paragraphs) {
		$str_before = '';
		foreach ($paragraphs as $paragraph) {
			$str_before .= $paragraph;
		}
		return $str_before . $str;
	}
	return $str;
}

/**
 * Replaces double line-breaks with paragraph elements.
 * 这个函数用来转换换行符字符串为<br />标记，并把双换行符作为一个新的段落的开始，在前一段加入</p>，并在新的段落加上<p>。
 * 
 * A group of regex replaces used to identify text formatted with newlines and
 * replace double line-breaks with HTML paragraph tags. The remaining
 * line-breaks after conversion become <<br />> tags, unless $br is set to '0'
 * or 'false'.
 *
 * @since 0.71
 *
 * @param string $pee The text which has to be formatted.
 * @param int|bool $br Optional. If set, this will convert all remaining line-breaks after paragraphing. Default true.
 * @return string Text which has been converted into correct paragraph tags.
 */
function wpautop($pee, $br = 1) {

	if ( trim($pee) === '' )
		return '';
	$pee = $pee . "\n"; // just to make things a little easier, pad the end
	$pee = preg_replace('|<br />\s*<br />|', "\n\n", $pee);
	// Space things out a little
	$allblocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|option|form|map|area|blockquote|address|math|style|input|p|h[1-6]|hr|fieldset|legend|section|article|aside|hgroup|header|footer|nav|figure|figcaption|details|menu|summary)';
	$pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee);
	$pee = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $pee);
	$pee = str_replace(array("\r\n", "\r"), "\n", $pee); // cross-platform newlines
	if ( strpos($pee, '<object') !== false ) {
		$pee = preg_replace('|\s*<param([^>]*)>\s*|', "<param$1>", $pee); // no pee inside object/embed
		$pee = preg_replace('|\s*</embed>\s*|', '</embed>', $pee);
	}
	$pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates
	// make paragraphs, including one at the end
	$pees = preg_split('/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY);
	$pee = '';
	foreach ( $pees as $tinkle )
		$pee .= '<p>' . trim($tinkle, "\n") . "</p>\n";
	$pee = preg_replace('|<p>\s*</p>|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace
	$pee = preg_replace('!<p>([^<]+)</(div|address|form)>!', "<p>$1</p></$2>", $pee);
	$pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee); // don't pee all over a tag
	$pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee); // problem with nested lists
	$pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee);
	$pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee);
	$pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)!', "$1", $pee);
	$pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
	if ($br) {
		$pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', create_function('$matches', 'return str_replace("\n", "<WPPreserveNewline />", $matches[0]);'), $pee);
		$pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee); // optionally make line breaks
		$pee = str_replace('<WPPreserveNewline />', "\n", $pee);
	}
	$pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', "$1", $pee);
	$pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee);
	if (strpos($pee, '<pre') !== false)
		$pee = preg_replace_callback('!(<pre[^>]*>)(.*?)</pre>!is', 'clean_pre', $pee );
	$pee = preg_replace( "|\n</p>$|", '</p>', $pee );

	return $pee;
}

/**
 * 构造评论摘要
 * @param str			原字符串
 * @param comment_id	评论 ID
 * @param start	        返回最新评论翻页参数
 */
function rc_substring($str, $comment_id, $start) {
	if (strpos($str,"...")) {
		return '<div class="rc_excerpt">'.$str.'<span class="rc_expand"><a rel="nofollow" href="javascript:void(0);" onclick="RCJS.detail(\''.$comment_id.'\',\''.__APP__.'/Comment/detailComment\',\''.$start.'\',\'Loading\');">»</a></span></div>';
	} else {
		return '<div class="rc_excerpt">'.$str.'</div>';
	}
}

/**
 * 构造评论表情
 */
function highslide_emoticons($static = false) {
	global $wpsmiliestrans;
	$closeAction = $static ? '' : 'return hs.close(\'emoticons\');';
	$emoticons = '';
	$smiled = array();
	foreach ($wpsmiliestrans as $tag => $grin) {
		if (!in_array($grin, $smiled)) {
			$smiled[] = $grin;
			$tag = str_replace(' ', '', $tag);
			$emoticons .= '<a href="javascript:void(0);" onclick="insertEmoticon(\' '.$tag.' \');' . $closeAction . '" style="margin-right:5px;"><img src="'. WEB_PUBLIC_PATH .'/Plugins/emoticons/smilies/'.$grin.'" alt="'.$tag.'"/></a>';
		}
	}

	$highslide_emoticon = '<script type="text/javascript" src="'.WEB_PUBLIC_PATH.'/Plugins/emoticons/emoticons.js"></script>';
	$highslide_emoticon .= '<a title="Pick an Emote" href="javascript:void(0);" onclick="return hs.htmlExpand(this, { contentId: \'emoticons\' } )" class="highslide">';
	$highslide_emoticon .= '<img src="' . WEB_PUBLIC_PATH . '/Plugins/emoticons/smilies/icon_smile.gif" alt="emoticons" />';
	$highslide_emoticon .= '</a>';
	$highslide_emoticon .= '<div class="highslide-html-content" id="emoticons" style="width:200px;">';
	$highslide_emoticon .= '<div class="highslide-body">';
	$highslide_emoticon .= $emoticons;
	$highslide_emoticon .= '</div>';
	$highslide_emoticon .= '<div class="highslide-header">';
	$highslide_emoticon .= '<ul>';
	$highslide_emoticon .= '<li class="highslide-close"><a href="#" onclick="return hs.close(this)">Close</a></li>';
	$highslide_emoticon .= '</ul>';
	$highslide_emoticon .= '</div>';
	$highslide_emoticon .= '</div>';

	echo $highslide_emoticon;
}

?>